package com.haoan.index.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * 使用 RedisMessageListenerContainer 和 MessageListenerAdapter 监听过期事件。
 * 需要在 Redis 配置文件中启用 Keyspace Notifications
 * notify-keyspace-events Ex
 */
@Configuration
public class RedisNotifyConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@0__:expired"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisNotifyListener listener) {
        return new MessageListenerAdapter(listener, "handleMessage");
    }
}
